<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\AdminUser;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cookie;

class LoginController extends Controller
{
    public function login(Request $request)
    {
        $username = $request->post('username');
        $password = $request->post('password');
        if (!$username || !$password) {
            return response()->json(['code' => 400, 'message' => '账号或密码不能为空']);
        }

        $user = \App\Models\AdminUser::where('username', $username)
            ->where('password', $password)
            ->first();
        if (!$user) {
            return response()->json(['code' => 400, 'message' => '用户不存在']);
        }

        $token = md5(time() . rand(1, 9999) . $user->id);
        $time = time() + 7200; // 设置token的过期时间为7200秒（2小时）
        $update = \App\Models\AdminUser::where('username', $username)
            ->where('password', $password)
            ->update(['token' => $token, 'over_time' => $time]);

        if (!$update) {
            return response()->json(['code' => 400, 'message' => '数据库错误']);
        }

        $token = encrypt($token);
        $cookie = cookie('user_token', $token, 7200);

        $data = [
            'user_id' => $user->id
        ];
        return response()->json(['code' => 200, 'message' => '成功', 'data' => $data])->cookie($cookie);
    }

    public function logout(Request $request)
    {
        $token = request()->cookie('user_token');
        $decrypted_token = decrypt($token);
        AdminUser::where('token', $decrypted_token)
            ->update(['token' => '', 'over_time' => 0]);
        return response()->json(['code' => 200, 'message' => '成功', 'data' => []])->withCookie(Cookie::forget('user_token'));
    }
}
